#-*- coding:utf-8 -*-
from PIL import Image,ImageDraw,ImageFont
from concurrent.futures import ThreadPoolExecutor
import os,re
#from getAlbbPici import isNeeded
'''
常有方法
Image.format 识别图像格式或来源，如果图像不是从文件读取的，值是None
Image.mode 图像的色彩模式 L灰度图像 RGB彩色图像 CMYK出版图像
Image.size 识别图像的宽高 单位为px，返回值是元组类型
im.info 输出与图像相关的数据的信息，返回字典类型
Image.open(img_path) 通过文件路径打开图像
Image.open(BytesIO(img_bytes)) 通过二进制文件流打开图像
Image.new(mode,size,color) 使用给定的模式、大小和颜色创建新图像
Image.show() 展示图像，会弹出一个展示窗口
Image.resise((size,size)) 调整图像宽高
Image.rotate(angle) 旋转图像
Image.save(filename,format) 保存图像，filename 图像名称或路径 format 保存模式，默认为RGB
img1.paste(img2, (10,10)) 将图像img2粘贴到图像img1上，并指定位置，默认为(0,0) 表示在左上点粘贴
————————————————
版权声明：本文为CSDN博主「haeasringnar」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
原文链接：https://blog.csdn.net/haeasringnar/article/details/103895140
'''

'''
根据正则替换字符
_exp:正则表达式
_repl:需要的字符
_str:要操作的字符串
'''
def altstr(_exp,_repl,_str):
    return re.sub(_exp,_repl,_str)
'''
参数：
place=(x,y)|x-宽，y-高
'''
def addWatermark(from_img,txt,to_img,place=None,txt_size=50):
    img = Image.open(from_img).convert('RGBA')
    s_img_w,s_img_h = img.size
    mark = Image.new('RGBA',img.size,(0,0,0,0))
    fnt = ImageFont.truetype('./STKAITI.TTF',txt_size)
    font_w,font_h = fnt.getsize(txt)
    #print('text_w:%d;text_h:%d' % (font_w,font_h))
    draw = ImageDraw.Draw(mark)
    fill_value = (255,255,255,800)
    if place is not None:
        draw.text(place,txt,font=fnt,fill=fill_value)
    else:
        draw.text(((s_img_w-font_w//2)//2,(s_img_h-font_h*2)//2),txt,font=fnt,fill=fill_value)
    out = Image.alpha_composite(img,mark)
    out.save(altstr('\.[a-zA-Z]{3,4}','.png',to_img))

'''
两图片叠加
placeLeftTopXY:元组(x,y) 左上角坐标（宽度，高度）
target_file保存路径
'''
def blendPic(bk_img,fr_img,target_file_name_no_suffix,placeLeftTopXY=None):
    bk = Image.open(bk_img).convert('RGBA')
    fr = Image.open(fr_img).convert('RGBA')
    if placeLeftTopXY is None:
        bk_size = bk.size #(width,height)
        fr_size = fr.size
        bk.paste(fr,((bk_size[0]-fr_size[0])//2,(bk_size[1]-fr_size[1])//2))
    else:
        bk.paste(fr,placeLeftTopXY)
    #bk.show()
    bk.save(target_file_name_no_suffix + '.png')

'''
获取文件list
'''
def getPicList(dirPath):
    picList = []
    for p in os.listdir(dirPath):
        full_p = os.path.join(dirPath,p)
        if os.path.isfile(full_p):
            picList.append(full_p)
    return picList

kv_name = {'1': 'alabama state', '2': 'alaska state', '3': 'arizona state', '4': 'arkasas','5':'california','6':'colorado','7':'connecticut','8':'delaware','9':'florida','10':'georgia','11':'hawaii','12':'idaho','13':'illinois','14':'indiana','15':'iowa','16':'kansas','17':'kentucky','18':'louisiana','19':'maine','20':'maryland','21':'massachusetts','22':'michigan','23':'minesota','24':'mississippi','25':'missouri','26':'montana','27':'nebraska','28':'nevada','29':'new hampshire','30':'new jersey','31':'new mexico','32':'new york','33':'north carolina','34':'north dakota','35':'ohio','36':'oklahoma','37':'oklahoma','38':'oregon','39':'pennsylvania','40':'rhode island','41':'south carolina','42':'south dakota','43':'tennessee','44':'texas','45':'UTAH','46':'vermont','47':'virginia','48':'washington','49':'west virginia','50':'wisconsin','51':'wyoming'}
us_state = {'alabama state': '阿拉巴马州', 'alaska state': '阿拉斯加州', 'arizona state': '亚利桑那州', 'arkasas': '阿肯色州', 'california': '加利福尼亚州', 'colorado': '科罗拉多州', 'connecticut': '康涅狄格州', 'delaware': '特拉华', 'florida': '佛罗里达', 'georgia': '佐治亚州', 'hawaii': '夏威夷', 'idaho': '爱达荷', 'illinois': '伊利诺伊', 'indiana': '印第安纳州', 'iowa': '爱荷华州', 'kansas': '堪萨斯州', 'kentucky': '肯塔基州', 'louisiana': '路易斯安那', 'maine': '缅因', 'maryland': '马里兰州', 'massachusetts': '马萨诸塞', 'michigan': '密西根', 'minesota': '明尼苏达州', 'mississippi': '密西西比州', 'missouri': '密苏里', 'montana': '蒙大拿', 'nebraska': '内布拉斯加州', 'nevada': '内华达', 'new hampshire': '新罕布什尔州', 'new jersey': '新泽西', 'new mexico': '新墨西哥州', 'new york': '纽约州', 'north carolina': '北卡罗来纳州', 'north dakota': '北达科他州', 'ohio': '俄亥俄州', 'oklahoma': '俄克拉荷马', 'oregon': '俄勒冈', 'pennsylvania': '宾夕法尼亚', 'rhode island': '罗得岛', 'south carolina': '南卡罗来纳', 'south dakota': '南达科塔', 'tennessee': '田纳西州', 'texas': '德克萨斯州', 'UTAH': '犹他州', 'vermont': '佛蒙特', 'virginia': '佛吉尼亚', 'washington': '华盛顿州', 'west virginia': '西弗吉尼亚州', 'wisconsin': '威斯康辛', 'wyoming': '怀俄明州'}

'''
叠加图片
'''
def processBlendPic():
    from_path = r'C:/E/work_myself/python_study/process-img/chepai_origin/'
    bg_path = r'C:/E/work_myself/python_study/process-img/chepai_bg_fix/'
    to_path = r'C:/E/work_myself/python_study/process-img/chepai_ename/'
    chepaiList = getPicList(from_path)
    #bgList = getPicList(bg_path)
    poolt = ThreadPoolExecutor(max_workers=8)
    for i in range(len(chepaiList)):
        bg_index = i//10
        if bg_index == 0:
            bg_index = 1
        pic_index = i+1
        current_cppic = chepaiList[i]
        current_pic_index = current_cppic.split('/')[-1].split('.')[0]
        #print(current_pic_index,current_cppic)
        #blendPic(bg_path+str(bg_index)+'.jpg',chepaiList[i],to_path+kv_name[current_pic_index]+'-'+current_pic_index)
        poolt.submit(blendPic,bg_path+str(bg_index)+'.jpg',chepaiList[i],to_path+kv_name[current_pic_index]+'-'+current_pic_index)
    poolt.shutdown()

'''
加水印
'''
def processAddMark():
    from_path = r'C:/E/work_myself/python_study/process-img/chepai_ename/'
    to_path = r'C:/E/work_myself/python_study/process-img/text_pic/'
    chepaiList = getPicList(from_path)
    poolt = ThreadPoolExecutor(max_workers=8)
    for _f in chepaiList:
        #print(_f)
        _key = _f.split('/')[-1].split('-')[0]
        _text = '%s(%s)' % (us_state[_key],_key)
        to_file = _f.replace(from_path,to_path)
        #print(_f,_text,to_file)
        #addWatermark(_f,_text,to_file)
        poolt.submit(addWatermark,_f,_text,to_file)
    poolt.shutdown()


if __name__ == '__main__':
    try:
        pass
        #processBlendPic()
        #processAddMark()
        txt = 'hello\nworld!'
        addWatermark('./utility/pic/10.png',txt,'./make.png')
    except Exception as ex:
        print('Found error:%s' % str(ex))
